import AsyncStorage from '@react-native-community/async-storage';
import {
  OPEN_GUEST_ENTRY,
  PROBLEM_WEBVIEW,
  STORAGE_KEY_APP_CONFIG
} from '../constant';
import { GetAppConfigRes } from '../api/app/getAppConfig';

interface ProblemWebviewProps {
  needDownload: boolean;
  problemWebviewName: string;
}

let appConfigRes: GetAppConfigRes;
let isOpenGuestEntry = false; // 是否打开游客入口
let problemWebview: ProblemWebviewProps = {
  needDownload: true,
  problemWebviewName: 'web20210618-1'
}; // 互动题webview

AsyncStorage.getItem(STORAGE_KEY_APP_CONFIG).then((res: any): void => {
  if (res) {
    appConfigRes = JSON.parse(res);
  }
});

AsyncStorage.getItem(PROBLEM_WEBVIEW).then((res: any): void => {
  if (res) {
    problemWebview = JSON.parse(res);
  }
});

export const setAppConfig = (data: GetAppConfigRes): void => {
  appConfigRes = data;
  AsyncStorage.setItem(STORAGE_KEY_APP_CONFIG, JSON.stringify(data));
};

export const getAppConfigInfo = (): GetAppConfigRes => {
  return appConfigRes;
};

export const setIsOpenGuestEntry = (val: boolean): void => {
  isOpenGuestEntry = val;
  AsyncStorage.setItem(OPEN_GUEST_ENTRY, JSON.stringify(val));
};

export const getIsOpenGuestEntry = (): boolean => {
  return isOpenGuestEntry;
};

export const setProblemWebview = (val: Partial<ProblemWebviewProps>): void => {
  problemWebview = { ...problemWebview, ...val };
  AsyncStorage.setItem(PROBLEM_WEBVIEW, JSON.stringify(problemWebview));
};

export const getProblemWebview = (): ProblemWebviewProps => {
  return problemWebview;
};
